
const { Op } = require("sequelize");

const Duty = require('../model/duty.model')

const { queryUtil,dutyWhereUtil } = require('../utils/query.util')

class DutyService {
    async createDuty(duty) {
        console.log(duty)
        // const res = await Duty.create(duty)

        //今天的时间
        // const start = new Date(new Date().toLocaleDateString()).getTime();
        // console.log(start);
        // // //明天的时间
        // const end = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1;
        // console.log(end);
        const whereOpt=dutyWhereUtil(duty.empId)

        const [res, created] = await Duty.findOrCreate({
            where: whereOpt, defaults: duty
        })
        return created ? res.dataValues : created
    }

    async updateByEmpId(duty) {
        const whereOpt=dutyWhereUtil(duty.empId)
        const { empId, ...newDuty } = duty
        const data = await Duty.findOne({ where: whereOpt })
        if (!data) {
            return '今日未签到，不可签退'
        }
        const res = await Duty.update(newDuty, { where: whereOpt })
        return res[0] > 0 ? '签退成功' : '签退失败'
    }

    async queryAll(pageNum, pageSize, whereOpt) {

        const { startTime, endTime, empName } = whereOpt
        const where = {}
        if (startTime && endTime) {
            where['signInTime'] = {
                [Op.between]: [startTime, endTime]
            }
        }
        if (empName) {
            where['empName'] = {
                [Op.like]: '%' + empName + '%'
            }
        }
        const res = await queryUtil(pageNum, pageSize, where, Duty)
        return res
    }
}

module.exports = new DutyService()